package com.platform.modules.app.service;


import com.alibaba.fastjson.JSONObject;
import com.platform.common.utils.Constant;
import com.platform.common.utils.RestResponse;
import com.platform.modules.mall.entity.MallOrderEntity;
import com.platform.modules.mall.entity.MallUserEntity;
import com.platform.modules.mall.service.MallOrderService;
import com.platform.modules.sys.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class PayChannelUtil {

    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private PayService payService;
    @Autowired
    private MallOrderService orderService;

    private static final String PAY_CHANNEL_CODE="PAY_CHANNEL";
    private static final String PAY_CHANNEL_WECHAT="WECHAT";
    private static final String PAY_CHANNEL_FUIOU="FUIOU";

    public RestResponse pay(MallUserEntity loginUser, JSONObject jsonParam){
        String type = sysConfigService.getValue(PAY_CHANNEL_CODE, PAY_CHANNEL_WECHAT);
        if (PAY_CHANNEL_WECHAT.equals(type)){
            /**微信支付*/
           return payService.payPrepay(loginUser,jsonParam);
        }else if (PAY_CHANNEL_FUIOU.equals(type)){
            /**富友支付*/

        }
        return RestResponse.error("请求失败，请重试");
    }


    @Transactional(rollbackFor = Exception.class)
    public RestResponse refund(String orderId,String userId){
        MallOrderEntity orderInfo = orderService.getById(orderId);
        if (null == orderInfo) {
            return RestResponse.error("订单已取消！");
        }
        if (!userId.equals(orderInfo.getUserId())) {
            return RestResponse.error("非法操作！");
        }

        if (orderInfo.getOrderStatus().equals(Constant.OrderStatus.TK.getValue()) || orderInfo.getOrderStatus().equals(Constant.OrderStatus.THTK.getValue())) {
            return RestResponse.error("订单已退款！");
        }

        if (!orderInfo.getPayStatus().equals(Constant.PayStatus.YFK.getValue())) {
            return RestResponse.error("订单未付款，不能退款！");
        }
        String type = sysConfigService.getValue(PAY_CHANNEL_CODE, PAY_CHANNEL_WECHAT);
        if (PAY_CHANNEL_WECHAT.equals(type)){
            /**微信退款*/
            orderService.update(orderInfo);
            return payService.refund(orderInfo);
        }else if (PAY_CHANNEL_FUIOU.equals(type)){
            /**富友退款*/

        }
        return RestResponse.error("请求失败，请重试");
    }

}
